<?php
namespace app\api\controller;
use app\common\model as M;
use service\AliMessageService;
use think\Cache;
use think\Session;

/**
 * 发送短信验证码
 */
class PublicApi extends \app\api\ApiBase
{
    public $model = '\app\admin\model\system\SystemConfig';

    /**
     * 发送短信验证码
     * @param  [type] $mobile [description]
     * @return [type]         [description]
     */
    public function send_sms ()
    {
        $mobile = request()->post('mobile' , '');

        if( !isMobile($mobile) ) return $this->returnFail('请输入正确的手机号码!');

    	$cache_key = "is_phone_code".$mobile;
        $time = Session::get($cache_key,'routine');

        if($time < time()+60) Session::delete($cache_key,'routine');

        if( Session::has($cache_key,'routine') && $time < time()) return $this->returnFail('您发送验证码的频率过高,请稍后再试!');

        $code = AliMessageService::getVerificationCode();

        $res = AliMessageService::sendmsg($mobile,$code);
        if ( $res->Code == 'OK' ) {
            M\SmsCode::set(['tel'=>$mobile,'code'=>$code,'last_time'=>time()+300]);
            Session::set($cache_key,time()+60,'routine');

            return $this->returnSuccess($res);
        }
        return $this->returnFail($res->Message);
    }

    /**
     * 登录、注册
     * @return [type] [description]
     */
    public function login ()
    {
        $user_info = M\User::get_login();
        if ( !empty($user_info) ) return $this->returnSuccess($user_info);

        $type    = $this->request->post('type' , 'sms');
        $mobile  = $this->request->post('mobile' , '');
        $code    = $this->request->post('code' , '');

        if ( !isMobile($mobile) ) return $this->returnFail('请输入正确的手机号码!');

        try {
            $res = false;
            if ( $type == 'sms' ) {
                if ( $code == '' ) return $this->returnFail('请输入短信验证码!');

                $valid_sms_code = M\SmsCode::valid_sms_code($mobile , $code);
                if ( $valid_sms_code === false ) return $this->returnFail('验证码校验失败');

                $res = M\User::sms_login($mobile , $this->org_id);
            }

            if ( $type == 'password' ) {
                if ( $code == '' ) return $this->returnFail('请输入密码!');
                $res = M\User::password_login($mobile , $code , $this->org_id);
            }

            if ( $res !== false ) return $this->returnSuccess($res);
        } catch (\Exception $e ) {
            p($e);
            return $this->returnFail($e->getMessage());
        }

        return $this->returnFail('登录失败，请稍后重试!');
    }
}//Class End